<?php
/**
 * Created by PhpStorm.
 * User: CCJK
 * Date: 2018/4/17
 * Time: 9:40
 */

namespace AppBundle\Controller;

use AppBundle\Common\Log;
use AppBundle\Entity\Product;
use AppBundle\Event\OrderEvent;
use AppBundle\EventSubscriber\OrderEventSubscriber;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class LuckyController extends Controller
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction()
    {
        $number = rand(0, 100);

        return new Response(
            '<html><body>Lucky number: '.$number.'</body></html>'
        );
    }

    /**
     * @Route("/api/lucky/number")
     */
    public function apiNumberAction()
    {
        $data = array(
            'lucky_number' => rand(0, 100),
        );

//        return new Response(
//            json_encode($data),
//            200,
//            array('Content-Type' => 'application/json')
//        );
        return new JsonResponse($data);
    }

    /**
     * @Route("/lucky/number2/{count}")
     */
    public function number2Action($count)
    {
        $numbers = array();
        for ($i = 0; $i < $count; $i++) {
            $numbers[] = rand(0, 100);
        }
        $numbersList = implode(', ', $numbers);

        return new Response(
            '<html><body>Lucky numbers: '.$numbersList.'</body></html>'
        );
    }


    /**
     * @Route("/lucky/number4/{count}" ,name="number4")
     * @param $count
     * @param Request $request
     * @return Response
     */
    public function number4Action($count, Request $request)
    {

        $dispatcher = new EventDispatcher();
        $orderSubscriber = new OrderEventSubscriber();
        $dispatcher->addSubscriber($orderSubscriber);

        $orderEvent = new OrderEvent("event id ".$count);
        $dispatcher->dispatch('order.create', $orderEvent);


        $list = $this->getDoctrine()
            ->getRepository('AppBundle:Product')
            ->findAll();
        if ($list) {
            for ($i = 0; $i < count($list); $i++) {
                Log::log($list[$i]);
            }
        }
        $this->get("log")->info("log log log log");
        $numbers = array();
        for ($i = 0; $i < $count; $i++) {
            $numbers[] = rand(0, 100);
        }

        //  echo("number4");

        return $this->render(
            'lucky/number3.html.twig',
            array('luckyNumberList' => $numbers, 'request' => $request)
        );
    }

    /**
     * @Route("/lucky/all" ,name="all")
     * @return Response
     */
    public function allAction()
    {


        $list = $this->getDoctrine()
            ->getRepository('AppBundle:Product')
            ->findAll();
        //->findBy(array('name' => "Keyboard"), array('id' => 'DESC'));

        $this->get("my_mailer")->printInfo();
        $this->get("log")->info("log log log log");

        return $this->render(
            'lucky/allproducts.html.twig',
            array('products' => $list)
        );
    }


    /**
     * @Route("/lucky/add")
     * @param Request $request
     */
    public function addProduct(Request $request)
    {

        $name = $request->get("name");
        $price = $request->get("price");
        $description = $request->get("description");
        if (!$name) {
            $data = array(
                'name' => "please input name",
            );

            return new JsonResponse($data);
        }
        if (!$price) {
            $data = array(
                'price' => "please input price",
            );

            return new JsonResponse($data);
        }
        if (!$description) {
            $data = array(
                'description' => "please input description",
            );

            return new JsonResponse($data);
        }
        $product = new Product();
        $product->setName($name);
        $product->setPrice($price);
        $product->setDescription($description);
        $em = $this->getDoctrine()->getManager();
        // tells Doctrine you want to (eventually) save the Product (no queries yet)
        // 告诉Doctrine你希望（最终）存储Product对象（还没有语句执行）
        $em->persist($product);
        // actually executes the queries (i.e. the INSERT query)
        // 真正执行语句（如，INSERT 查询）
        $em->flush();
        $data = array(
            'result' => "true",
        );

        return new JsonResponse($data);
    }

    /**
     * @Route("/lucky/file")
     */
    public function getFileAction()
    {
        //默认路径在web下面
//        return new BinaryFileResponse("F:/temp/blog/web/files/test.php");
//        return new BinaryFileResponse("files/test.php");
        return new BinaryFileResponse("robots.txt");
//        return new BinaryFileResponse(".htaccess");
    }

    public function showAction($count)
    {
        // ...

        // /blog/my-blog-post
        $url = $this->generateUrl(
            'number4',
            array('count' => $count)
        );
    }
}